const $console = require("Console")
const mysql = require("mysql")
const config = require("./package").db
const base = require("./package").base
const jdbc = require("./jdbc")
const util = require("./ejs-utils")
const readFromSql = async tableName => {
  const connection = mysql.createConnection({
    host: config.host,
    port: config.port,
    user: config.user,
    password: config.pwd,
    database: config.database
  })
  const query = util.p({
    fn: connection.query,
    target: connection
  })
  const res = await query(`show full columns from ${tableName}`)
  let tableInfo = await query(
    `select TABLE_COMMENT from information_schema.TABLES where TABLE_SCHEMA='${
      config.database
    }' and TABLE_NAME= '${tableName}';`
  )
  let title = tableName
  if (tableInfo.length > 0) {
    title = tableInfo[0].TABLE_COMMENT
  }
  const className = tableName.replace(/_(\w)/g, (a, b) => b.toUpperCase())
  const ClassName = className.replace(/\w/, v => v.toUpperCase())
  const vueName = tableName.replace(/_/g, "-")
  const result = {
    className,
    tableName,
    title,
    ClassName,
    vueName,
    fields: [],
    fields_no_id: [],
    ids: [],
    domain_package: config.domain_package,
    service_pakcage: config.service_pakcage
  }
  const fileds = []
  res.forEach(function(e) {
    let len,
      lx = e.Type.replace(/\(.*\)/, function(x) {
        x.replace(/[0-9]+/, y => (len = y))
        return ""
      }).toLowerCase(),
      isId = e.Key === "PRI",
      field = {
        isId,
        len,
        comment: e.Comment || e.Field,
        column: e.Field.toLowerCase(),
        type: jdbc.lxMap[lx],
        name: e.Field.replace(/_(\w)/g, (a, b) => b.toUpperCase()),
        Name: e.Field.replace(/(^|_)(\w)/g, (a, b, c) => c.toUpperCase())
      }
    if (isId === true) {
      result.ids.push(field)
    } else {
      result.fields_no_id.push(field)
    }
    result.fields.push(field)
    fileds.push(field.column)
  })
  result.fieldNames = fileds.join(",")
  connection.end()
  return result
}
const domain = config.domain_package.replace(/\./g, util.sep)
const service = config.service_pakcage.replace(/\./g, util.sep)
console.log(domain)
console.log(service)
const actions = {
  code: {
    name: "代码生成",
    avs: []
  }
}

actions.code.avs.push({
  action: "code-pl",
  help: "生成后台代码,命令格式为 .code-pl 表名",
  async fn(tableName) {
    let result
    try {
      result = await readFromSql(tableName)
    } catch (e) {
      $console.error("数据库连接失败,或者表名错误!")
      return false
    }
    Object.assign(result, {
      user: util.user,
      time: util.now()
    })
    // domain
    let txt = await util.render("domain.java", result)
    await util.writeFile(
      txt,
      `${util.baseDir}${util.sep}src${util.sep}main${util.sep}java${
        util.sep
      }${domain}`,
      `${result.ClassName}.java`
    )
    // sql
    txt = await util.render("sql.md", result)
    await util.writeFile(
      txt,
      `${util.baseDir}${util.sep}src${util.sep}main${util.sep}resources${
        util.sep
      }sql`,
      `${result.className}.md`
    )
    // service
    txt = await util.render("service.java", result)
    await util.writeFile(
      txt,
      `${util.baseDir}${util.sep}src${util.sep}main${util.sep}java${
        util.sep
      }${service}${util.sep}platform`,
      `${result.ClassName}Service.java`
    )
    //vue
    txt = await util.render("add-button.vue", result)
    await util.writeFile(
      txt,
      `${util.baseDir}${util.sep}node${util.sep}${base.pc}${util.sep}src${
        util.sep
      }views${util.sep}${result.vueName}${util.sep}list`,
      `add-button.vue`
    )
    txt = await util.render("edit-button.vue", result)
    await util.writeFile(
      txt,
      `${util.baseDir}${util.sep}node${util.sep}${base.pc}${util.sep}src${
        util.sep
      }views${util.sep}${result.vueName}${util.sep}list`,
      `edit-button.vue`
    )
    txt = await util.render("form-data.js", result)
    await util.writeFile(
      txt,
      `${util.baseDir}${util.sep}node${util.sep}${base.pc}${util.sep}src${
        util.sep
      }views${util.sep}${result.vueName}${util.sep}list`,
      `form-data.js`
    )
    txt = await util.render("form.vue", result)
    await util.writeFile(
      txt,
      `${util.baseDir}${util.sep}node${util.sep}${base.pc}${util.sep}src${
        util.sep
      }views${util.sep}${result.vueName}${util.sep}list`,
      `form.vue`
    )
    txt = await util.render("search-data.js", result)
    await util.writeFile(
      txt,
      `${util.baseDir}${util.sep}node${util.sep}${base.pc}${util.sep}src${
        util.sep
      }views${util.sep}${result.vueName}${util.sep}list`,
      `search-data.js`
    )
    txt = await util.render("list.vue", result)
    await util.writeFile(
      txt,
      `${util.baseDir}${util.sep}node${util.sep}${base.pc}${util.sep}src${
        util.sep
      }views${util.sep}${result.vueName}`,
      `list.vue`
    )
    txt = await util.render("route.js", result)
    await util.writeFile(
      txt,
      `${util.baseDir}${util.sep}node${util.sep}${base.pc}${util.sep}src${
        util.sep
      }router${util.sep}modules-login`,
      `${result.vueName}.js`
    )
    $console.success("生成完毕!")
  }
})
actions.code.avs.push({
  action: "code-wb",
  help: "生成前台接口,命令格式为 .code-wb 表名",
  async fn(tableName) {
    let result
    try {
      result = await readFromSql(tableName)
    } catch (e) {
      $console.error("数据库连接失败,或者表名错误!")
      return false
    }
    Object.assign(result, {
      user: util.user,
      time: util.now()
    })
    // domain
    let txt = await util.render("domain.java", result)
    await util.writeFile(
      txt,
      `${util.baseDir}${util.sep}src${util.sep}main${util.sep}java${
        util.sep
      }${domain}`,
      `${result.ClassName}.java`
    )
    // sql
    txt = await util.render("sql.md", result)
    await util.writeFile(
      txt,
      `${util.baseDir}${util.sep}src${util.sep}main${util.sep}resources${
        util.sep
      }sql`,
      `${result.className}.md`
    )
    // service
    txt = await util.render("interface.java", result)
    await util.writeFile(
      txt,
      `${util.baseDir}${util.sep}src${util.sep}main${util.sep}java${
        util.sep
      }${service}${util.sep}web`,
      `${result.ClassName}Service.java`
    )
    $console.success("生成完毕!")
  }
})
module.exports = actions
